package com.mocoder.chatdemo.protocol;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
import java.util.Base64;

import com.mocoder.chatdemo.controller.MainController;
import com.mocoder.chatdemo.model.ChatMsg;
import com.mocoder.chatdemo.model.MsgModel;
import com.mocoder.chatdemo.model.UserInfo;
import com.mocoder.chatdemo.util.ByteUtil;
import com.mocoder.chatdemo.util.ConfigUtil;
import javafx.application.Platform;

/**
 * Created by Administrator on 2018/3/11.
 */
public class MsgServer {

    public static void startServer(MainController controller) {

        String name = ConfigUtil.properties.getProperty("name");
        String imgDataStr = ConfigUtil.properties.getProperty("imgdata");
        byte[] imgData = null;
        if (imgDataStr != null && !imgDataStr.isEmpty()) {
            imgData = Base64.getDecoder().decode(imgDataStr);
        }
        long updatetime = Long.valueOf(ConfigUtil.properties.getProperty("updatetime", "0"));
        ProtocolHelper.setUserInfo(null, new UserInfo(name, imgData, updatetime));

        Thread t = new Thread() {
            @Override
            public void run() {
                System.out.println("listener start up,local ip:" + ProtocolHelper.getLocalAdress().getHostAddress());
                DatagramSocket socket = null;
                try {
                    socket = new DatagramSocket(3333);
                    byte[] findMsg = new byte[50000];
                    DatagramPacket packet = new DatagramPacket(findMsg, findMsg.length);
                    while (true) {
                        socket.receive(packet);
                        byte[] msg = Arrays.copyOfRange(packet.getData(), packet.getOffset(),
                            packet.getOffset() + packet.getLength());
                        handleRequest(new MsgModel(packet.getAddress(), packet.getPort(), msg), controller);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (socket != null) {
                        socket.close();
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }

    private static void handleRequest(MsgModel msgObj, MainController controller) throws UnsupportedEncodingException {
        byte[] msg = msgObj.getMsg();
        if (ByteUtil.equals(ByteUtil.HEADER_USERSCAN_REQ, msg, 0, 5)) {
            ProtocolHelper.sentUserInfoUpdateResp(msgObj);
            UserInfo userInfo = UserInfo.decode(msgObj.getMsg());
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    controller.updateFriendList(msgObj.getHost(), userInfo);
                }
            });
        } else if (ByteUtil.equals(ByteUtil.HEADER_USERSCAN_RES, msg, 0, 5)) {
            UserInfo userInfo = UserInfo.decode(msgObj.getMsg());
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    controller.updateFriendList(msgObj.getHost(), userInfo);
                }
            });
        } else if (ByteUtil.equals(ByteUtil.HEADER_CHAT_MSG_ROOM_REQ, msg, 0, 5)) {
            ProtocolHelper.sentEnsureResponse(msgObj);
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    String chatMsg = ChatMsg.decode(msg);
                    controller.addChatMsg(msgObj.getHost(), chatMsg, true);
                }
            });
        } else if (ByteUtil.equals(ByteUtil.HEADER_CHAT_MSG_USER_REQ, msg, 0, 5)) {
            ProtocolHelper.sentEnsureResponse(msgObj);
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    String chatMsg = ChatMsg.decode(msg);
                    controller.addChatMsg(msgObj.getHost(), chatMsg, false);
                }
            });
        }
    }

}
